import * as echarts from 'echarts'
import 'echarts-wordcloud'
import { useEffect, useRef, useState } from 'react'
export default function WordcloudChart({ data }) {
    const chartRef = useRef(null)
    const [myChart, setMyChart] = useState()
    let timer = useRef(null)
    const resizeObserver = new ResizeObserver(entries => {
        timer && clearTimeout(timer)
        timer = setTimeout(() => {
            myChart && myChart.resize();
        }, 100)
    });
    const renderChart = () => {
        myChart.clear()
        const option = {
            series: [
                {
                    type: "wordCloud",
                    // 网格大小，各项之间间距
                    gridSize: 30,
                    // 形状 circle 圆，cardioid  心， diamond 菱形，
                    // triangle-forward 、triangle 三角，star五角星
                    shape: 'circle',
                    // 字体大小范围
                    sizeRange: [20, 50],
                    // 文字旋转角度范围
                    rotationRange: [0, 0],
                    // 旋转步值
                    rotationStep: 90,
                    // 自定义图形
                    // maskImage: maskImage,
                    left: 'center',
                    top: 'center',
                    right: null,
                    bottom: null,
                    // 画布宽
                    width: '100%',
                    // 画布高
                    height: '100%',
                    // 是否渲染超出画布的文字
                    drawOutOfBound: false,
                    textStyle: {
                        color: function () {
                            const colors = ['#165DFF', '#6aca37',
                                '#05a4b6', '#f93920', '#f0b114']
                            return colors[parseInt(Math.random() * (colors.length))];
                        },
                        emphasis: {
                            shadowBlur: 10,
                            shadowColor: '#2ac'
                        }
                    },
                    data: data
                }
            ]
        };
        // 4. 使用图表参数完成图表的渲染
        option && myChart.setOption(option);
        window.addEventListener("resize", function () {
            myChart.resize();
        });
    }
    useEffect(() => {
        setMyChart(echarts.init(chartRef.current))
    }, [])
    useEffect(() => {
        // 保证dom可用 才进行图表的渲染
        myChart && renderChart()
        resizeObserver.observe(chartRef.current);
        return () => resizeObserver.disconnect();
    }, [myChart, data])
    return <div ref={chartRef} style={{ width: '100%', height: '100%' }}></div>
}
